package org.unidata.mdm.rest.meta.service;

import java.util.Objects;

import org.unidata.mdm.core.type.security.SecurityToken;
import org.unidata.mdm.core.util.SecurityUtils;
import org.unidata.mdm.meta.exception.MetaExceptionIds;
import org.unidata.mdm.rest.system.service.AbstractRestService;
import org.unidata.mdm.system.exception.PlatformFailureException;

/**
 * @author Mikhail Mikhailov on Oct 22, 2020
 * Does simple security filtering for top level objects.
 */
public abstract class AbstractFilteringRestService extends AbstractRestService {
    /**
     * Constructor.
     */
    public AbstractFilteringRestService() {
        super();
    }

    protected boolean allow(String topLevelName) {

        if (Objects.isNull(topLevelName)) {
            return false;
        }

        SecurityToken token = SecurityUtils.getSecurityTokenForCurrentUser();
        try {

            if (token == null || token.getUser().isAdmin()
             || token.getRightsMap().containsKey(SecurityUtils.ADMIN_SYSTEM_MANAGEMENT)
             || token.getRightsMap().containsKey(SecurityUtils.ADMIN_DATA_MANAGEMENT_RESOURCE_NAME)) {
                return true;
            }

            return token.getRightsMap().containsKey(topLevelName);
        } catch (Exception e) {
            final String message = "Metadata service failed to retrieve data [{}].";
            throw new PlatformFailureException(message, e, MetaExceptionIds.EX_META_ENTITY_NOT_FOUND);
        }
    }
}
